<?php

namespace TpAmis\Traits;


trait FileManagerTrait
{

    private $root_path;
    private $public_path;
    private $upload_path;
    private $directory;


    /**
     * 构造函数，设置目录路径
     *
     */
    public function base()
    {

        $this->root_path = root_path();
        $this->public_path = root_path() . 'public' . DIRECTORY_SEPARATOR;
        $this->upload_path = $this->public_path . 'upload' . DIRECTORY_SEPARATOR;

    }
    protected function getFileList($path = '')
    {
        return $this->getFilesAndDirectories($path);

    }
    protected function getDirNode($path = '')
    {
        $pathItems = $this->pathToNestedArray($path);
       
        $GroupButtions = [];
        foreach ($pathItems as $pathNod => $path) {
            $path = preg_replace('#[\\\\/]+#', '/', $path);

            $Event = [
                'click' => [
                    'actions' => [
                        ["actionType" => 'rebuild', "componentId" => "fileManager", 'args' => ["path" => $path]],
                        ["actionType" => "reload", "componentId" => "fileManagerList", "data" => ["path" => '${event.data.item.path}']]
                    ],
                ],
            ];
            $GroupButtions[] = amis()->Button()->label($pathNod)->onEvent($Event);
        }
        $FilePaths = amis()->ButtonGroup()->buttons($GroupButtions);

        return ['body' => $FilePaths, 'path' => $path];
    }

    protected function fileSelect($name, $lable = '', $NodepathUrl = '', $FileListUrl = '')
    {
        return amis()->PickerControl($name, $lable)->source(
            amis()->BaseApi()->methon('post')->url($FileListUrl)
        )
            ->valueField('path')
            ->labelField('name')
            ->pickerSchema(
                amis()->CRUD2Table()
                    ->name('thelist')
                    ->id('fileManagerList')
                    ->headerToolbar([
                        amis()->Service()->id('fileManager')->name('fileManagerApi')->schemaApi(
                            amis()->BaseApi()
                                ->url($NodepathUrl . '?' . getUrlQuery(['path' => '${path}']))
                                ->method('post')
                        )
                    ])
                    ->columns([
                        amis()->TableColumn('type', '类型'),
                        amis()->TableColumn('icon', '图标')->type('image'),
                        amis()->TableColumn('name', '名称'),
                        amis()->TableColumn('site', '大小'),
                        amis()->TableColumn('ext', '后缀'),
                        // amis()->TableColumn('path', '路径'),
                    ])
                    ->rowClassNameExpr('${type === "dir" ? "" : "no-click"}', )
                    ->onEvent(
                        [
                            'rowClick' => [
                                'actions' => [
                                    [
                                        "actionType" => 'rebuild',
                                        "componentId" => "fileManager",
                                        'args' => [
                                            "path" => '${event.data.item.path}'
                                        ]
                                    ],
                                    [
                                        "actionType" => "reload",
                                        "data" => [
                                            "path" => '${event.data.item.path}'
                                        ]
                                    ]

                                ]
                            ]
                        ]
                    )
            );
    }


    /**
     * 获取指定目录下的所有文件和文件夹名称，并区分文件和文件夹
     *
     * @return array 文件和文件夹信息列表
     */
    public function getFilesAndDirectories($directory = '')
    {
        $this->base();

        $items = [];
        foreach (new \DirectoryIterator($this->upload_path . $directory) as $fileInfo) {
            if ($fileInfo->isDot()) {
                continue; // 跳过 . 和 ..
            }

            $item = [
                'name' => $fileInfo->getFilename(),
                'ext' => $fileInfo->getExtension(),
                'site' => $this->trans_byte($fileInfo->getSize()),
                'type' => $fileInfo->isFile() ? 'file' : 'dir',
            ];

            if ($fileInfo->isDir()) {
                $item['icon'] = request()->domain() . join('/', explode('\\', '\static\admin\images\dir.png'));
            } else {

                $item['icon'] = request()->domain() . str_replace($this->public_path, '', $fileInfo->getPathname());
            }

            $item['path'] = DIRECTORY_SEPARATOR . str_replace($this->upload_path, '', $fileInfo->getPathname());
            $item['path'] = str_replace('\\\\', '\\', $item['path']);
            $item['test'] = [$fileInfo->getPathname(), $directory];
            $items[] = $item;
        }

        return $items;
    }
    /**
     * 计算文件大小
     * @param int $byte
     * @return string
     */
    private function trans_byte(int $byte)
    {
        if ($byte == 0) {
            return '';
        }
        $KB = 1024;
        $MB = 1024 * $KB;
        $GB = 1024 * $MB;
        $TB = 1024 * $GB;
        if ($byte < $KB) {
            return $byte . " B";
        } elseif ($byte < $MB) {
            return round($byte / $KB, 2) . " KB";
        } elseif ($byte < $GB) {
            return round($byte / $MB, 2) . " MB";
        } elseif ($byte < $TB) {
            return round($byte / $GB, 2) . " GB";
        } else {
            return round($byte / $TB, 2) . " TB";
        }
    }

    /**
     * 将文件路径转换为数组，数组从高到底每一个值都比上一个值多一个路径节点名称
     *
     * @return array 路径数组
     */
    public function pathToNestedArray($directory = '')
    {
        $this->base();
        $directory = str_replace($this->upload_path, '', $directory);
        // 分割路径为节点
        $parts = explode(DIRECTORY_SEPARATOR, $directory);
        
        // 初始化结果数组
        $result = [];
        $currentPath = '';

        // 遍历每个路径节点
        foreach ($parts as $part) {
            // 拼接当前路径
            $currentPath .= ($currentPath === '' ? '/' : DIRECTORY_SEPARATOR) . $part;

            // 添加到结果数组
            $part = ($part == '' ? '/' : $part);
            $result[$part] = $currentPath;
        }

        return $result;
    }
}
